package com.ja.controller.v1;

import com.alibaba.fastjson.JSON;
import com.ja.config.WebsiteStateConfig;
import com.ja.domain.*;
import com.ja.sevice.*;
import com.ja.util.*;
import com.ja.util.v1.Result;
import com.ja.util.v1.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 项目名称：cp
 * 类名称：UserController
 * 类描述：   用户的注册管理类
 * 创建人：GL
 * 创建时间：2018年10月10日 上午11:27:43
 */
@Controller
@RequestMapping("/v1/u")
public class V1UserController {

    @Autowired
    private IUserService userService;

   /* @Autowired
    private IV1UserService iv1UserService;
*/
    @Autowired
    private LiushuiService liushuiService;

    @Autowired
    private IBankService bankService;

    @Autowired
    private ISystemConfigService systemConfigService;

    @Autowired
    private LuckyRecordService luckyRecordService;

    @Autowired
    private YunyingbbService yunyingbbService;

    @Autowired
    private AgencyCenterSevice agencyCenterSevice;

    @RequestMapping("/userInfo")
    public void userInfo() {
    }

    @RequestMapping("/daili")
    public void daili() {
    }

    @RequestMapping("/editUserSelfData")
    public void editUserSelfData() {
    }

    @RequestMapping("/safe")
    public void safe() {
    }

    @RequestMapping("/set")
    public void set() {
    }

    /**
     *
     *----TODO：用户信息
     *
     */

    /**
     * 方法名：checkUser
     * 描述：    根据用户名查询用户信息
     * 参数：    @param name 用户名
     * 参数：    @return
     *
     * @return: JsonResult
     */
    @RequestMapping("/checkUser")
    @ResponseBody
    public JsonResult checkUser(String name) {
        User user = userService.checkUser(name);
        if (user != null) {
            return new JsonResult("用户存在", 1);
        }
        return new JsonResult("用户不存在", 0);
    }

    /**
     * 方法名：findUserInfo
     * 描述：    查询用户信息
     * 参数：    @param session
     * 参数：    @return
     *
     * @return: JsonResult
     */
    @RequestMapping("/userInfos")
    @ResponseBody
    public JsonResult findUserInfo(HttpSession session) {
        User user = (User) session.getAttribute("user");
        user = userService.getUserByid(user.getId());
        User users = new User();
        users.setName(user.getName());
        users.setNicheng(user.getNicheng());
        users.setAvatar(user.getAvatar());
        users.setTelephone(user.getTelephone());
        users.setQq(user.getQq());
        users.setBalance(user.getBalance());
        users.setFid(user.getFid());
        users.setIcode(user.getIcode());
        users.setAgent_type(user.getAgent_type());
        users.setState(user.getState());
        users.setStatu(user.getStatu());
        return new JsonResult("success", users);
    }

    /**
     * 方法名：changePass
     * 描述：   修改用户密码
     * 参数：    @param pass 原密码
     * 参数：    @param npass 新密码
     * 参数：    @param request
     * 参数：    @param session
     * 参数：    @return
     *
     * @return: JsonResult
     */
    @RequestMapping("/changePass")
    @ResponseBody
    public JsonResult changePass(HttpSession session, HttpServletRequest request, String pass, String npass) {
        User user = (User) session.getAttribute("user");
        pass = DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(pass.getBytes()).getBytes());
        npass = DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(npass.getBytes()).getBytes());
        if (!pass.equals(user.getPass())) {
            return new JsonResult("0", "旧密码输入错误");
        }
        user.setPass(npass);
        userService.updateUserInfo(user);
        User users = userService.login(user.getName(), npass);
        session.setAttribute("user", users);
        new WebSocketJson(8, user.getName(), "你的密码已修改请从新登陆").send();
        SessionListenerUtil.singleLogin(request, user.getName());
        return new JsonResult("1", "修改成功");
    }

    /**
     * 方法名：updateUserInfo
     * 描述：    修改用户资料
     * 参数：    @param nicheng 用户昵称
     * 参数：    @param request
     * 参数：    @return
     *
     * @return: JsonResult
     */
    @ResponseBody
    @RequestMapping("/changeA1")
    public JsonResult updateUserInfo(HttpServletRequest request, String nicheng) {
        User u = (User) request.getSession().getAttribute("user");
        return new JsonResult(String.valueOf(userService.updateUserInfo(u)), userService.getUserByid(u.getId()));
    }

    /**
     * 方法名：img
     * 描述：    批量查询用户的头像
     * 参数：    @param str 用户id
     * 参数：    @return
     *
     * @return: JsonResult
     */
    @RequestMapping("/img")
    @ResponseBody
    public JsonResult img(String str) {
        String[] id = str.split(",");
        List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < id.length; i++) {
            list.add(new Integer(id[i].trim()));
        }
        List<User> user = liushuiService.img(list);
        return new JsonResult("success", user);
    }


    /**
     *
     * ----TODO：代理中心管理
     *
     */

    /**
     * 方法名：userInvitationLink
     * 描述：     生成用户的推广链接
     * 参数：    @param session
     * 参数：    @param request
     * 参数：    @return
     *
     * @return: JsonResult
     */
    @ResponseBody
    @RequestMapping("/yqm")
    public JsonResult userInvitationLink(HttpSession session, HttpServletRequest request) {
        User user = (User) session.getAttribute("user");
        if (user.getState() == 2) {
            return new JsonResult("试玩账号无法申请代理，请注册正式账号", "试玩账号无法申请代理，请注册正式账号");
        }
        String icode = "";
        String domain = request.getScheme() + "://" + request.getServerName();
        String uid = UUID.randomUUID().toString().replaceAll("-", "").substring(25).toUpperCase() + user.getId();
        if (user.getIcode() != null) {
            String[] code = user.getIcode().split("\\?");
            if (code[0].equals(domain)) {
                icode = user.getIcode();
            } else {
                icode = domain + "?" + code[1];
                user.setIcode(icode);
            }
        } else {
            icode = domain + "?ref_code=" + uid;
            user.setIcode(icode);
            user.setAgent_type(1);
        }
        userService.updateUserInfo(user);
        user = userService.getUserByid(user.getId());
        User users = new User();
        users.setName(user.getName());
        users.setNicheng(user.getNicheng());
        users.setAvatar(user.getAvatar());
        users.setBalance(user.getBalance());
        users.setIcode(user.getIcode());
        return new JsonResult(icode, user);
    }

    /**
     *
     * ------------用户的充值反水-流水记录
     *
     */

    /**
     * 查询用户的反水记录
     *
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/fanshuijl")
    public JsonResult fanshuijl(HttpSession session) {
        User user = (User) session.getAttribute("user");
        List<Liushui> fs = liushuiService.getOneFanshui(user.getId());
        return new JsonResult("fanshuijl", fs);
    }

    /**
     * 查询用户的流水记录
     *
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/details")
    public JsonResult details(HttpSession session) {
        User user = (User) session.getAttribute("user");
        return new JsonResult(null, liushuiService.getLiushui(user.getId()));
    }

    /**
     * 查询用户已读的流水记录
     *
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping("/duliushui")
    public JsonResult duliushui(String ids) {
        String idss[] = ids.split(",");
        for (int i = 0; i < idss.length; i++) {
            liushuiService.upliushui(Integer.parseInt(idss[i]));
        }
        return new JsonResult("duliushui", null);
    }

    @RequestMapping("/bank")
    public ModelAndView bank(HttpSession session) {
        User user = (User) session.getAttribute("user");
        BankCard bank = bankService.getBankByUid(user.getId());
        return new ModelAndView("u/bank").addObject("bank", bank).addObject("message", "pageTest");
    }

    /**
     *
     * -------------用户的每日签到
     *
     */

    /**
     * 每日签到页面
     */
    @RequestMapping("/signIn")
    public String signIn() {
        return "/u/meiriqiandao";
    }

    /**
     * 查询用户是否已签到
     *
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/signInFlag")
    public JsonResult signInFlag(HttpSession session) {
        User user = (User) session.getAttribute("user");
        String message = "0";
        String signMoney = "0.00";
        if (user.getState() == 2) {
            return new JsonResult("20", "试玩账号不能参与签到!");
        }
        Liushui water = liushuiService.checkSigIn(user.getId(), DateUtil.findFormatDate());
        TodayRecord record = yunyingbbService.findOperateRecord("", "", user.getName(), 2);
        if (water != null) {
            message = "6";
            signMoney = water.getBdjine() + "";
        }
        User u = userService.getUserByid(user.getId());
        return new JsonResult(message, u.getBalance() + ";" + signMoney + ";" + record.getMrqiandao());
    }

    /**
     * 用户进行签到
     *
     * @param session
     * @return
     */
    @RequestMapping("/signInUser")
    @ResponseBody
    public JsonResult signInUser(HttpSession session) {
        User users = (User) session.getAttribute("user");
        if (users.getState() == 2) {
            return new JsonResult("20", "试玩账号不能参与签到!");
        }
        JsonResult jsonResult = liushuiService.signInUserIng(users);
        return jsonResult;
    }

    /**
     * 查询用户的 签到记录
     *
     * @param session
     * @return
     */
    @RequestMapping("/record")
    @ResponseBody
    public JsonResult record(HttpSession session) {
        User user = (User) session.getAttribute("user");
        List<Liushui> water = liushuiService.getSignInRecord(user.getId());
        return new JsonResult("record", water);
    }

    /**
     *
     * -----幸运大抽奖
     *
     */

    /***
     * 幸运大转盘页面
     */
    @RequestMapping("/luckys")
    public String lucky() {
        return "/include/zhuanpan";
    }

    /**
     * 用户抽奖次数
     *
     * @param session
     * @return
     */
    @RequestMapping("/luckyCount")
    @ResponseBody
    public JsonResult luckyCount(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user.getState() == 2) {
            return new JsonResult("0", "试玩账号没有抽奖记录");
        }
        LuckyCount counts = luckyRecordService.getOneLuckyCount(user.getId());
        return new JsonResult("luckyCount", counts.getCount());
    }

    /**
     * 用户抽奖记录
     *
     * @param session
     * @return
     */
    @RequestMapping("/luckyRecord")
    @ResponseBody
    public JsonResult luckyRecord(HttpSession session) {
        User user = (User) session.getAttribute("user");
        List<LuckyRecord> records = luckyRecordService.getOneLuckyRecord(user.getId());
        return new JsonResult("luckyRecord", records);
    }

    /**
     * 随机抽奖记录
     *
     * @param session
     * @return
     */
    @RequestMapping("/mathRecord")
    @ResponseBody
    public JsonResult mathRecord(HttpSession session) {
        List<LuckyRecord> records = luckyRecordService.getMathLuckyRecord();
        return new JsonResult("mathRecord", records);
    }

    /**
     * 用户抽奖
     *
     * @param session
     * @return
     */
    @RequestMapping("/luckyReckon")
    @ResponseBody
    public JsonResult luckyReckon(HttpSession session) {
        synchronized (this) {
            User users = (User) session.getAttribute("user");
            User user = userService.getUserByid(users.getId());
            if (user.getState() == 2) {
                return new JsonResult("0", "试玩账号不能参与抽奖");
            }
            LuckyCount counts = luckyRecordService.getOneLuckyCount(user.getId());
            if (counts.getCount() < 1) {
                return new JsonResult("抽奖次数已用完,请充值后在来", 10);
            } else if (Integer.parseInt(WebsiteStateConfig.configs.get("luckyFlag")) == 0) {
                return new JsonResult("幸运抽奖已暂时关闭,下次开启时间请留意公告!!!", 10);
            }
            List<LuckyLotter> lotter = luckyRecordService.getAllLuckyLotter();
            String[] datas = getPrizeIndex(lotter).split(",");
            int a1 = Integer.parseInt(datas[0]);
            double money = Double.parseDouble(datas[1]);
            int a2 = (int) (Math.random() * 3 + 2);
            String type = "";
            switch (a1) {
                case 1:
                    type = lotter.get(0).getLotterType();
                    break;
                case 2:
                    type = lotter.get(1).getLotterType();
                    break;
                case 3:
                    type = lotter.get(2).getLotterType();
                    break;
                case 4:
                    type = lotter.get(3).getLotterType();
                    break;
                case 5:
                    type = lotter.get(4).getLotterType();
                    break;
                case 6:
                    type = lotter.get(5).getLotterType();
                    break;
                case 7:
                    type = lotter.get(6).getLotterType();
                    break;
                default:
                    type = lotter.get(7).getLotterType();
                    break;
            }
            LuckyRecord record = new LuckyRecord();
            record.setName(user.getName());
            record.setType(type);
            record.setMoney(money);
            record.setScope(a2);
            record.setCreateTime(DateUtil.getCurrTime());
            record.setUserid(user.getId());
            luckyRecordService.addLuckyRecord(record);
            counts.setCount(counts.getCount() - 1);
            counts.setCreateTime(DateUtil.getCurrTime());
            luckyRecordService.updateLuckyCount(counts);
            String orderNum = "ZP" + DateUtil.DateFormatOrderNum() + user.getId();
            if (money != 0.00) {
                liushuiService.addActivityRecord(user, orderNum, true, money, "幸运转盘", 3);
            }
            return new JsonResult("sucess", type + "," + a2 + "," + money);
        }
    }

    /**
     * 第N个random个就是抽中的奖品
     */
    public String getPrizeIndex(List<LuckyLotter> lotter) {
        DecimalFormat dec = new DecimalFormat("#0.00");
        int random = 7;
        double money = 0.00;
        double sumWeight = 0;
        double random1 = 0.00;
        try {
            for (LuckyLotter ls : lotter) {/** 计算总权重 */
                sumWeight += ls.getRebate();
            }
            double randomNumber;
            randomNumber = Math.random();
            double d1 = 0.00;/** 根据随机数在所有奖品分布的区域并确定所抽奖品 */
            double d2 = 0.00;
            for (int i = 0; i < lotter.size(); i++) {
                d2 += (lotter.get(i).getRebate() / sumWeight);
                if (i == 0) {
                    d1 = 0;
                } else {
                    d1 += (lotter.get(i - 1).getRebate() / sumWeight);
                }
                if (randomNumber > d1 && randomNumber < d2) {
                    random = i;
                    Double min = Double.parseDouble(lotter.get(i).getLotterMoney().split(",")[0]);
                    Double max = Double.parseDouble(lotter.get(i).getLotterMoney().split(",")[1]);
                    do {
                        random1 = (Math.random() * max);
                        random1 = Double.parseDouble(dec.format(random1));
                    } while (random1 < min);
                    money = random1;
                    random += 1;
                    return random + "," + money;
                }
            }
        } catch (Exception e) {
            System.out.println("抽奖异常：" + e.getMessage());
        }
        random += 1;
        return random + "," + money;
    }


    /**
     *
     * --------系统通知
     *
     *
     */

    /**
     * 方法名：systemNotice
     * 描述：     通知页面
     * 参数：    @param session
     * 参数：    @return
     *
     * @return: ModelAndView
     */
    @RequestMapping("/systemNotice")
    public ModelAndView systemNotice(HttpSession session) {
        return new ModelAndView("u/systemNotice");
    }

    /**
     * 方法名：systemNoticeWD
     * 描述：     未读流水
     * 参数：    @param paging
     * 参数：    @param session
     * 参数：    @return
     *
     * @return: String
     */
    @ResponseBody
    @RequestMapping("/systemNoticeWD")
    public String systemNoticeWD(PagingData paging, HttpSession session) {
        User user = (User) session.getAttribute("user");
        paging.setAllCount(liushuiService.getWDLiushuiCounts(user.getId(), 0));
        paging.setList(liushuiService.getWDLiushui(paging.getStartIndex(), paging.getLineCount(), user.getId(), 1));
        return PagingData.pagingData(paging);
    }

    /**
     * 方法名：systemNoticeData
     * 描述：     已读流水
     * 参数：    @param paging
     * 参数：    @param session
     * 参数：    @return
     *
     * @return: String
     */
    @ResponseBody
    @RequestMapping("/systemNoticeYD")
    public String systemNoticeData(PagingData paging, HttpSession session) {
        User user = (User) session.getAttribute("user");
        paging.setAllCount(liushuiService.getWDLiushuiCounts(user.getId(), 1));
        paging.setList(liushuiService.getYDLiushui(paging.getStartIndex(), paging.getLineCount(), user.getId(), 1));
        return PagingData.pagingData(paging);
    }


    /**
     * 方法名：Querychatrecord
     * 描述：     查询聊天室的聊天记录
     * 参数：    @param session
     * 参数：    @return
     *
     * @return: JsonResult
     */
    @RequestMapping("/Querychatrecord")
    @ResponseBody
    public JsonResult Querychatrecord(HttpSession session) {
        User user1 = (User) session.getAttribute("user");
        SimpleDateFormat sdf = new SimpleDateFormat("dd");
        List<Lsltjl> list = liushuiService.query(sdf.format(new Date()));
        return new JsonResult(String.valueOf(user1.getId()), list);
    }


    /**
     * 方法名：panduanshifudenglu
     * 描述：      判断用户是否登录
     * 参数：    @param session
     * 参数：    @return
     *
     * @return: JsonResult
     */
    @RequestMapping("/panduanshifudenglu")
    @ResponseBody
    public JsonResult panduanshifudenglu(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return new JsonResult(null, 0);
        }
        return new JsonResult(user.getAvatar(), 1);
    }


    /**
     *
     * ----TODO：重复的接口
     *
     */


    /**
     * 查询用户的余额
     *
     * @param session
     * @return
     */
    @RequestMapping("/userMoney")
    @ResponseBody
    public JsonResult userMoney(HttpSession session) {
        User user = (User) session.getAttribute("user");
        User u = userService.getUserByid(user.getId());
        session.setAttribute("user", u);
        return new JsonResult(user.getStatu() + "", u.getBalance());
    }

    /**
     * 查询用户的信息
     *
     * @param session
     * @return
     */
    @RequestMapping("/userName")
    @ResponseBody
    public JsonResult userName(HttpSession session) {
        User user = (User) session.getAttribute("user");
        User u = userService.getUserByid(user.getId());
        return new JsonResult(String.valueOf(u.getBalance()), u.getName(), u.getVip(), u.getGamePlayer());
    }


    /**
     *
     * ----TODO： 更换地址的接口
     *
     */

    /**
     * 方法名：code
     * 描述：     生成验证码
     * 参数：    @param request
     * 参数：    @param response
     * 参数：    @throws Exception
     *
     * @return: void
     */
    @RequestMapping("/code")
    public void code(HttpServletRequest request, HttpServletResponse response) throws Exception {
        CodeUtil.createdCode(request, response);
    }

    /**
     * 用户注册
     *
     * @param request        当前请求对象
     * @param session        session对象
     * @param name           用户名称
     * @param pass           用户密码
     * @param invitationCode 邀请码
     * @return
     */

    // TODO b
    @RequestMapping(value = "/register", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public synchronized String register(HttpServletRequest request, HttpSession session, String name, String pass,
                                            String invitationCode) {

        Map<String,Object> map =new HashMap<>();
        List<Map<String,Object>> array = new ArrayList<>();

        synchronized (this) { // TODO 为什么要用串行化
            try {
                String refCode = (String) session.getAttribute("refCode");//拿到用户当前访问的连接 TODO b 什么意思？
                refCode.split("\\?");//拆分报错就不是用户的推广连接 有可能是总代理的代理连接
            } catch (Exception e) {
                //如果拆分报错  那就是没有用邀请链接
               /* if (invitationCode == null || "".equals(invitationCode)) {
                    map.put("5", "请填写邀请码!如果没有邀请码请联系QQ客服");
                }
                if (agencyCenterSevice.pueryagencyInvitationCode(invitationCode) == null) {
                    map.put("5", "请填写邀请码!如果没有邀请码请联系QQ客服");
                }*/
            }
            if (name.length() > 10 || name.length() < 4) {
                map.put("code", "10008");
                map.put("msg","用户名的长度必须4-10位");
              //  map.put("5", "用户名的长度必须4-10位");
            }
            if (UserNameUtil.isSpecialChar(name)) {
                map.put("code", "10001");
                map.put("msg", "用户名不能包含特殊字符");

            }
            if (UserNameUtil.isContainChinese(name)) {
                map.put("code", "10001");
                map.put("msg", "用户名不能包含特殊字符");
            }
            User iuser = userService.checkUser(name);
            if (iuser != null) {
                map.put("code","10007");
                map.put("msg", "用户名已存在");

            }
           /* try {
                String codee = (String) session.getAttribute("code");
                if (!codee.toUpperCase().equals(code.toUpperCase())) {
                    map.put("2", "验证码错误!");
                    //  return new JsonResult("2", "验证码错误!");
                }
            } catch (Exception e) {
                map.put("0", "请刷新验证码!");
               // new JsonResult("0", "请刷新验证码!");
            }*/

            //注册ip地址
            String ip = IpAddrUtil.getIpAddr(request);
            if (!systemConfigService.ipCheck(ip, 1)) {
              map.put("code","10009");
              map.put("msg","注册次数过多，请明日注册!");
               // map.put("3", "注册次数过多，请明日注册!");
              //  return new JsonResult("3", "注册次数过多，请明日注册!");
            }

            //用户注册
            int num = userService.register2(session, request, name, pass, invitationCode, ip);
            String md5 = DigestUtils.md5DigestAsHex(pass.getBytes());
            String pwd = DigestUtils.md5DigestAsHex(md5.getBytes());
            /*String pwd = null;
            try {
                pwd = DataEncryptUtil.encryptBASE64(pass.getBytes());//加密
            } catch (Exception e) {
                e.printStackTrace();
            }*/
            User user = userService.login(name, pwd);
            map.put("user",user);
          //  session.setAttribute("user", user);

            WebSocketJson w = new WebSocketJson(4, user.getName());
            w.sendAllHt();
            Set<User> set = SessionListenerUtil.onlineNum(request);
            if (set.size() > 0) {
                WebSocketJson w1 = new WebSocketJson(2, set.size());
                w1.sendHt();
            }
            map.put(String.valueOf(num), "恭喜你,注册成功");

            Integer id = user.getId();
            String idStr=id+"";
            try {
                map.put("token",DataEncryptUtil.encryptBASE64(idStr.getBytes()));//用BASE64加密
            } catch (Exception e) {
                e.printStackTrace();
            }
            array.add(map);
            return JSON.toJSONString(array);
        }
    }


    @RequestMapping(value = "/winnerList", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String winnerList() {
     return buildWInner();
    }

    private String buildWInner() {
        String[] str = {  "北京PK拾","二分PK拾", "幸运赛马","幸运飞艇", "重庆时时彩", "二分时时彩", "天津时时彩","新疆时时彩", "广东快乐十分", "重庆快乐十分", "安徽11选5",
                "广东11选5", "江西11选5", "山东11选5", "上海11选5", "排列三", "福彩3D", "安徽快3", "广西快3", "江苏快3", "北京快3","三分快3","香港六合彩","五分六合彩",
                "北京28","幸运28","百家乐" };
        List<Winner> list = new ArrayList<Winner>();
        for (int i = 1; i < str.length-1; i++) {
            Winner winner = new Winner();
            winner.setLottryName(str[createLotteryName(str.length - 1)]);
            winner.setName(createUserName(4)+"*");
            winner.setWinnerMoney(new BigDecimal(new Random().nextInt(10000)));
            list.add(winner);
        }
        return JSON.toJSONString(list);
    }

    /***
     * 方法名：createLotteryName
     * 描述：    随机取彩种名称                    TODO
     * 参数：    @param num
     * 参数：    @return
     * @return: int
     */
    public int createLotteryName(int num) {
        while (true) {
            int ii = (int) (1 + Math.random() * num);
            if (num >= ii) {
                return ii;
            }
        }
    }


    /**
     * 方法名：createUserName
     * 描述：    随机生成用户名                   TODO
     * 参数：    @param length
     * 参数：    @return
     * @return: String
     */
    public String createUserName(int length) {
        // 定义一个字符串（A-Z，a-z，0-9）即62位；
        String str = "zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
        // 由Random生成随机数
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        // 长度为几就循环几次
        for (int i = 0; i < length; ++i) {
            // 产生0-61的数字
            int number = random.nextInt(62);
            // 将产生的数字通过length次承载到sb中
            sb.append(str.charAt(number));
        }
        // 将承载的字符转换成字符串
        return sb.toString();
    }

    public static final class Winner {

        public String name;
        public BigDecimal winnerMoney;
        public String lottryName;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public BigDecimal getWinnerMoney() {
            return winnerMoney;
        }

        public void setWinnerMoney(BigDecimal winnerMoney) {
            this.winnerMoney = winnerMoney;
        }

        public String getLottryName() {
            return lottryName;
        }

        public void setLottryName(String lottryName) {
            this.lottryName = lottryName;
        }
    }

    @RequestMapping(value = "/totalMoney", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String totalMoney(HttpServletRequest request) {
        Random random = new Random();
        return  random.nextInt(500000000)+100000000+".21";

    }



    /**
     * 用户登录
     */
    @RequestMapping(value = "/login", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String login(HttpServletRequest request, String name, String pass) {
        String ip1 = IpAddrUtil.getIpAddr(request);
        Map<String,Object> map =new HashMap<>();
        userService.addTourists(ip1, "登录");
        User user = userService.login(name, DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(pass.getBytes()).getBytes()));
       map.put("user",user);
        if(user!=null) {
            if (user.getState() == 0) {
                //2 账号已被管理员禁用，请联系客服
                map.put("code","10004");
                map.put("msg","账号已被管理员禁用，请联系客服");
                //return new Result(ResultCode.FORBIDDEN);
            } else if (user.getState() == 1) {
                // 最后登录ip
                String ip = IpAddrUtil.getIpAddr(request);
                WhiteList whiteList = systemConfigService.findWhiteListByIP(ip);
                if (whiteList != null && whiteList.getStatus() == 0) {
                    //改ip已经被禁用，请更换ip重新登录
                    map.put("code","10005");
                    map.put("msg","该ip被禁用，请更换ip重新登录");
                  // return new Result(ResultCode.IPFORBIDDEN);
                }
                // 未登录时间
                String retime = user.getLastTime();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                long t1 = 0;
                String t3 ="";
                try {
                    t1 = sdf.parse(retime).getTime();
                    t3 = "未登录"+(int) (((new Date().getTime() - t1) / 1000) / 86400) + "天";
                } catch (ParseException e) {
                }
                user.setLastTime(DateUtil.getCurrTime());
                user.setNotTime(t3);
                user.setLastIp(ip);
                userService.updateUserInfo(user);
                new WebSocketJson(7,name,"你的账号在另外一个地方登陆，如果不是你本人操作请及时修改密码").send();
                SessionListenerUtil.singleLogin(request, name);
               map.put("user", user);
                // session.setAttribute("user", user);
                WebSocketJson w = new WebSocketJson(3,user.getName());
                w.sendAllHt();
                Set<User> set = SessionListenerUtil.onlineNum(request);
                if(set.size() > 0) {
                    WebSocketJson w1 = new WebSocketJson(2,set.size());
                    w1.sendAllHt();
                }
                map.put("code","10000");
                map.put("msg","登录成功");
              //  return new Result(ResultCode.SUCCESS);
            } else {
                SessionListenerUtil.singleLogin(request, name);
               map.put("user", user);
               // session.setAttribute("user", user);
                WebSocketJson w = new WebSocketJson(3,user.getName());
                w.sendAllHt();
                Set<User> set = SessionListenerUtil.onlineNum(request);
                if(set.size() > 0) {
                    WebSocketJson w1 = new WebSocketJson(2,set.size());
                    w1.sendAllHt();
                }
                map.put("code","10000");
                map.put("msg","登录成功");
                //return new Result(ResultCode.SUCCESS);
            }
        }else {
            map.put("code","10006");
            map.put("msg","账号或者密码错误");
           // map.put("5", "账号或者密码错误");
          //  return new Result(ResultCode.PASSERROR);//5账号密码错误
        }
        Integer id = user.getId();
        String idStr=id+"";
        try {
            map.put("token",DataEncryptUtil.encryptBASE64(idStr.getBytes()));//用BASE64加密
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(map);
    }

    /**
     * 方法名：tryPlayAcount
     * 描述：     生成试玩账号
     * 参数：    @return
     *
     * @return: JsonResult
     */
    @ResponseBody
    @RequestMapping(value = "/tryPlayAcount", produces = {"application/json;charset=UTF-8"})
    public String tryPlayAcount() {
        String str = "guest";
        Random random = new Random();
        Map<String,Object> map =new HashMap<>();
        while (true) {
            String acount = str + random.nextInt();
            User user = userService.checkUser(acount);
            if (user == null) {
                   map.put("success", acount);
                return JSON.toJSONString(map);
            }
        }
    }

    /**
     * 方法名：tryplay
     * 描述：    试玩帐号注册
     * 参数：    @param users
     * 参数：    @param name 用户名
     * 参数：    @param pass 用户密码
     * 参数：    @param session
     * 参数：    @param request
     * 参数：    @return
     *
     * @return: JsonResult
     */
    @RequestMapping(value = "/tryplay", produces = {"application/json;charset=UTF-8"},method = RequestMethod.POST)
    @ResponseBody
    public String tryplay(User user, HttpServletRequest request) {
        Map<String,Object> map =new HashMap<>();
     /*   User users = (User)session.getAttribute("user");*/
       /* if (users != null) {
            map.put("10", "你已经登录不可在试玩！");
            return JSON.toJSONString(map);
        }*/
        if (UserNameUtil.isSpecialChar(user.getName())) {
           // map.put("5", "用户名不能包含特殊字符!");
            map.put("code","10001");
            map.put("msg","用户名不能包含特殊字符!");
            return JSON.toJSONString(map);
        }
        if (user.getName().length() > 25 || user.getName().length() < 4) {
          //  map.put("5", "用户名的长度必须4-10位!");
            map.put("code","10001");
            map.put("msg","用户名的长度必须4-10位!");
            return JSON.toJSONString(map);
        }
        if (UserNameUtil.isContainChinese(user.getName())) {
            map.put("code","10001");
            map.put("msg","用户名不能包含特殊字符!");
            return JSON.toJSONString(map);
        }
        String ipAddress = IpAddrUtil.getIpAddr(request);
        if (!systemConfigService.ipCheck(ipAddress, 2)) {
            map.put("code","10002");
            map.put("msg", "试玩次数过多，请明日注册！");
            return  JSON.toJSONString(map);
        }
        synchronized (this) {
            userService.addTourists(ipAddress, "试玩账号");
            User iuser = userService.checkUser(user.getName());
            String pass = DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(user.getPass().getBytes()).getBytes());
            if (iuser != null) {
                if (!pass.equals(iuser.getPass())) {
                    map.put("code","10006");
                    map.put("msg", "密码错误,请重新登录或注册试玩账号！");
                    return JSON.toJSONString(map);
                } else {
                    /*session.setAttribute("user", iuser);*/
                    map.put("code","10000");
                   map.put("msg", "登录成功");
                    return JSON.toJSONString(map);
                }
            }
            user.setPass(pass);
            user.setRegisterIp(ipAddress);
            user.setLastIp(ipAddress);
            userService.userTryplay(user);//为试玩玩家注册
            User userInfo = userService.login(user.getName(), pass);
           /*session.setAttribute("user", userInfo);*/

            Integer id = user.getId();
            String idStr=id+"";
            try {
                map.put("token",DataEncryptUtil.encryptBASE64(idStr.getBytes()));//用BASE64加密
            } catch (Exception e) {
                e.printStackTrace();
            }
            map.put("code","10000");
            map.put("msg", "试玩玩家登录成功");
            map.put("user", userInfo);
            return JSON.toJSONString(map);
        }
    }

}
